package com.techblor.library.wechat.api.officialaccount;

import com.alibaba.fastjson.JSON;
import com.techblor.library.wechat.beans.result.BaseResult;
import com.techblor.library.wechat.beans.sns.Jscode2session;
import com.techblor.library.wechat.beans.sns.SnsToken;
import com.techblor.library.wechat.beans.user.SnsapiUserInfo;
import com.techblor.library.wechat.utils.HttpClientUtil;

import java.net.URLEncoder;

import static com.techblor.library.wechat.constants.WechatConstant.BASE_URL;


/**
 * 网页授权
 *
 * @author zhangceven
 */
public class SnsApi {

    /**
     * 微信开发第一步
     * 生成网页授权 URL
     *
     * @param appid           appid
     * @param redirect_uri    自动URLEncoder
     * @param snsapi_userinfo snsapi_userinfo
     * @param state           可以为空
     * @return url
     */
    public static String connectOauth2Authorize(String appid, String redirect_uri, boolean snsapi_userinfo, String state) {
        return connectOauth2Authorize(appid, redirect_uri, snsapi_userinfo, state, null);
    }

    /**
     * 微信开发第一步
     * 生成网页授权 URL  (第三方平台开发)
     *
     * @param appid           appid
     * @param redirect_uri    自动URLEncoder
     * @param snsapi_userinfo snsapi_userinfo
     * @param state           可以为空
     * @param component_appid 第三方平台开发，可以为空。
     *                        服务方的appid，在申请创建公众号服务成功后，可在公众号服务详情页找到
     * @return url
     */
    public static String connectOauth2Authorize(String appid, String redirect_uri, boolean snsapi_userinfo, String state, String component_appid) {
        try {
            String userinfo = snsapi_userinfo ? "snsapi_userinfo" : "snsapi_base";

            String url = "https://open.weixin.qq.com/connect/oauth2/authorize?"
                    + "appid=" + appid
                    + "&redirect_uri=" + URLEncoder.encode(redirect_uri, "utf-8")
                    + "&response_type=code"
                    + "&scope=" + userinfo
                    + "&state=" + state;

            if (component_appid != null) {
                url = url.concat("&component_appid=" + component_appid);
            }
            url = url.concat("#wechat_redirect");

            return url;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 微信网页授权第二步
     * 通过 code 换取网页授权access_token
     *
     * @param appid
     * @param secret
     * @param code
     * @return
     */
    public static SnsToken oauth2AccessToken(String appid, String secret, String code) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token"
                + "?appid=" + appid
                + "&secret=" + secret
                + "&code=" + code
                + "&grant_type=authorization_code";

        String result = HttpClientUtil.doGet(url);
        return JSON.parseObject(result, SnsToken.class);

    }

    /**
     * 微信网页授权第二步
     * 通过code换取网页授权access_token(第三方平台开发)
     *
     * @param appid
     * @param code
     * @param secret
     * @param component_appid
     * @param component_access_token
     * @return
     */
    public static SnsToken oauth2ComponentAccessToken(String appid, String code, String secret, String component_appid, String component_access_token) {
        String url = "https://api.weixin.qq.com/sns/oauth2/component/access_token"
                + "?appid=" + appid
                + "&code=" + code
                + "&grant_type=authorization_code"
                + "&component_appid=" + component_appid
                + "&component_access_token=" + component_access_token;

        String result = HttpClientUtil.doGet(url);
        return JSON.parseObject(result, SnsToken.class);

    }

    /**
     * 微信开发第三步：刷新access_token（如果需要）
     * 网页授权刷新access_token
     *
     * @param appid
     * @param refresh_token 微信网页授权第二步获取到的refresh_token
     * @return
     */
    public static SnsToken oauth2RefreshToken(String appid, String refresh_token) {
        String url = "https://api.weixin.qq.com/sns/oauth2/refresh_token"
                + "?appid=" + appid
                + "&grant_type=refresh_token"
                + "&refresh_token=" + refresh_token;

        String result = HttpClientUtil.doGet(url);
        return JSON.parseObject(result, SnsToken.class);
    }


    /**
     * 刷新access_token(第三方平台开发)
     *
     * @param appid
     * @param refresh_token
     * @param component_appid
     * @param component_access_token
     * @return
     */
    public static SnsToken oauth2ComponentRefreshToken(String appid, String refresh_token, String component_appid, String component_access_token) {
        String url = "https://api.weixin.qq.com/sns/oauth2/refresh_token"
                + "?appid=" + appid
                + "&grant_type=refresh_token"
                + "&refresh_token=" + refresh_token
                + "&component_appid=" + component_appid
                + "component_access_token=" + component_access_token;

        String result = HttpClientUtil.doGet(url);
        return JSON.parseObject(result, SnsToken.class);

    }

    /**
     * 检验授权凭证(access_token)是否有效
     *
     * @param access_token
     * @param openid
     * @return
     */
    public static BaseResult auth(String access_token, String openid) {
        String url = "https://api.weixin.qq.com/sns/auth"
                + "?access_token=" + access_token
                + "&openid=" + openid;

        String result = HttpClientUtil.doGet(url);
        return JSON.parseObject(result, BaseResult.class);

    }

    /**
     * 微信网页授权开发第四步：拉取用户信息(需scope为 snsapi_userinfo)
     *
     * @param access_token
     * @param openid
     * @param lang         国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语
     * @param emoji        表情解析方式
     * @return
     */
    public static SnsapiUserInfo snsUserInfo(String access_token, String openid, String lang, int emoji) {
        String url = "https://api.weixin.qq.com/sns/userinfo"
                + "?access_token=" + access_token
                + "&openid=" + openid
                + "&lang=" + lang;

        String result = HttpClientUtil.doGet(url);
        return JSON.parseObject(result, SnsapiUserInfo.class);
    }

    /**
     * 微信网页授权开发第四步：拉取用户信息(需scope为 snsapi_userinfo)
     *
     * @param access_token
     * @param openid
     * @param lang         国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语
     * @return
     */
    public static SnsapiUserInfo snsUserinfo(String access_token, String openid, String lang) {
        return snsUserInfo(access_token, openid, lang, 0);
    }

    /**
     * 登录凭证校验
     *
     * @param appId
     * @param secret
     * @param jsCode
     * @return
     */
    public static Jscode2session jscode2session(String appId, String secret, String jsCode) {
        String url = BASE_URL + "/sns/jscode2session"
                + "?appid=" + appId
                + "&secret=" + secret
                + "&js_code=" + jsCode
                + "&grant_type=authorization_code";

        String result = HttpClientUtil.doGet(url);
        return JSON.parseObject(result, Jscode2session.class);
    }

}
